package com.unis.service.analysis.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.unis.common.config.DS;
import com.unis.common.constant.Constants;
import com.unis.common.enums.QqlxEnum;
import com.unis.common.exception.app.AppRuntimeException;
import com.unis.common.secure.authc.UserInfo;
import com.unis.common.util.TemplateUtil;
import com.unis.dto.ResultDto;
import com.unis.mapper.analysis.ManulAnalysisMapper;
import com.unis.mapper.analysis.ScreenDataMapper;
import com.unis.mapper.analysis.SfMxJgListMapper;
import com.unis.mapper.analysis.YhkMxJgListMapper;
import com.unis.mapper.znzf.SfZtQqMapper;
import com.unis.mapper.znzf.YhkZtQqMapper;
import com.unis.model.analysis.AnalysisConditionModel;
import com.unis.model.analysis.ManulAnalysis;
import com.unis.model.analysis.SfMxJgList;
import com.unis.model.analysis.YhkMxJgList;
import com.unis.model.system.BankCode;
import com.unis.model.znzf.SfMxQq;
import com.unis.model.znzf.SfZtQq;
import com.unis.model.znzf.YhkMxQq;
import com.unis.model.znzf.YhkZtQq;
import com.unis.service.analysis.ManulAnalysisService;
import com.unis.service.impl.BaseServiceImpl;
import com.unis.service.system.BankCodeService;
import com.unis.service.znzf.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * <pre>
 * @see ManulAnalysisService
 * </pre>
 *
 * @author zcf
 * @version 1.0
 * @since 2020-03-26
 */
@Service("manulAnalysisService")
public class ManulAnalysisServiceImpl extends BaseServiceImpl implements ManulAnalysisService {
    private static final Logger logger = LoggerFactory.getLogger(ManulAnalysisServiceImpl.class);
    @Autowired
    private ManulAnalysisMapper manulAnalysisMapper;
    @Autowired
    private BankCodeService bankCodeService;
    @Autowired
    private ZnzfService znzfService;
    @Autowired
    private YhkZtQqService yhkZtQqService;
    @Autowired
    private YhkZtQqMapper yhkZtQqMapper;
    @Autowired
    private ZnzfQueueService znzfQueueService;
    @Autowired
    private SfZtQqService sfZtQqService;
    @Autowired
    private SfZtQqMapper sfZtQqMapper;
    @Autowired
    private SfMxQqService sfMxQqService;
    @Autowired
    private YhkMxQqService yhkMxQqService;
    @Autowired
    private ScreenDataMapper screenDataMapper;
    @Autowired
    private YhkMxJgListMapper yhkMxJgListMapper;
    @Autowired
    private SfMxJgListMapper sfMxJgListMapper;

    /**
     * @see ManulAnalysisService#insert(ManulAnalysis manulAnalysis)
     */
    @Override
    public int insert(ManulAnalysis manulAnalysis) throws Exception {
        if (manulAnalysis != null) {
//	        manulAnalysis.setPk(TemplateUtil.genUUID());
            //menu.setPk(getPk("seqName","jgdm","A"));

            return manulAnalysisMapper.insertSelective(manulAnalysis);
        } else {
            logger.error("ManulAnalysisServiceImpl.insert时manulAnalysis数据为空。");
            throw new AppRuntimeException("ManulAnalysisServiceImpl.insert时manulAnalysis数据为空。");
        }
    }

    /**
     * @see ManulAnalysisService#delete(String pk)
     */
    @Override
    public int delete(String pk) throws Exception {
        if (StringUtils.isBlank(pk)) {
            logger.error("ManulAnalysisServiceImpl.delete时pk为空。");
            throw new AppRuntimeException("ManulAnalysisServiceImpl.delete时pk为空。");
        } else {
            return manulAnalysisMapper.deleteByPrimaryKey(pk);
        }
    }

    /**
     * @see ManulAnalysisService#updateByPrimaryKey(ManulAnalysis manulAnalysis)
     */
    @Override
    public int updateByPrimaryKey(ManulAnalysis manulAnalysis) throws Exception {
        if (manulAnalysis != null) {
            if (StringUtils.isBlank(manulAnalysis.getPk())) {
                logger.error("ManulAnalysisServiceImpl.updateByPrimaryKey时manulAnalysis.Pk为空。");
                throw new AppRuntimeException("ManulAnalysisServiceImpl.updateByPrimaryKey时manulAnalysis.Pk为空。");
            }
            return manulAnalysisMapper.updateByPrimaryKeySelective(manulAnalysis);
        } else {
            logger.error("ManulAnalysisServiceImpl.updateByPrimaryKey时manulAnalysis数据为空。");
            throw new AppRuntimeException("ManulAnalysisServiceImpl.updateByPrimaryKey时manulAnalysis数据为空。");
        }
    }

    /**
     * @see ManulAnalysisService#queryManulAnalysisByPrimaryKey(String pk)
     */
    @Override
    public ManulAnalysis queryManulAnalysisByPrimaryKey(String pk) throws Exception {
        if (StringUtils.isBlank(pk)) {
            logger.error("ManulAnalysisServiceImpl.queryManulAnalysisByPrimaryKey时pk为空。");
            throw new AppRuntimeException("ManulAnalysisServiceImpl.queryManulAnalysisByPrimaryKey时pk为空。");
        } else {
            return manulAnalysisMapper.selectByPrimaryKey(pk);
        }
    }


    /**
     * @see ManulAnalysisService#queryAsObject(ManulAnalysis manulAnalysis)
     */
    @Override
    public ManulAnalysis queryAsObject(ManulAnalysis manulAnalysis) throws Exception {
        if (manulAnalysis != null) {
            return manulAnalysisMapper.selectOne(manulAnalysis);
        } else {
            logger.error("ManulAnalysisServiceImpl.queryAsObject时manulAnalysis数据为空。");
            throw new AppRuntimeException("ManulAnalysisServiceImpl.queryAsObject时manulAnalysis数据为空。");
        }
    }

    /**
     * @see ManulAnalysisService#queryCountByExample(Example example)
     */
    @Override
    public int queryCountByExample(Example example) throws Exception {
        if (example != null) {
            return manulAnalysisMapper.selectCountByExample(example);
        } else {
            logger.error("ManulAnalysisServiceImpl.queryCountByExample时example数据为空。");
            throw new AppRuntimeException("ManulAnalysisServiceImpl.queryCountByExample时example数据为空。");
        }
    }

    /**
     * @see ManulAnalysisService#queryListByExample(Example example)
     */
    @Override
    public List<ManulAnalysis> queryListByExample(Example example) throws Exception {
        if (example != null) {
            return manulAnalysisMapper.selectByExample(example);
        } else {
            logger.error("ManulAnalysisServiceImpl.queryListByExample时example数据为空。");
            throw new AppRuntimeException("ManulAnalysisServiceImpl.queryListByExample时example数据为空。");
        }
    }

    /**
     * @see ManulAnalysisService#queryPageInfoByExample(Example example, int pageNum, int pageSize)
     */
    @Override
    public PageInfo queryPageInfoByExample(Example example, int pageNum, int pageSize) throws Exception {
        if (example != null) {
            PageHelper.startPage(pageNum, pageSize);
            return new PageInfo(manulAnalysisMapper.selectByExample(example));
        } else {
            logger.error("ManulAnalysisServiceImpl.queryListByExample时example数据为空。");
            throw new AppRuntimeException("ManulAnalysisServiceImpl.queryListByExample时example数据为空。");
        }
    }

    /**
     * @see ManulAnalysisService#queryListByPage(Map parmMap, int pageNum, int pageSize)
     */
    @Override
    public ResultDto queryListByPage(Map parmMap, int pageNum, int pageSize) throws Exception {
        if (parmMap != null) {
            Example example = new Example(ManulAnalysis.class);
            example.setOrderByClause("create_date desc ");
            //example.setOrderByClause("rksj DESC,pk asc");设置排序
            Example.Criteria criteria = example.createCriteria();
            //criteria设置
            // = --> andEqualTo(field,value)
            // like --> andLike(field,likeValue)；likeValue 包含‘%’
            // is null --> andIsNull(field)
            // is not null --> andIsNotNull(field)
            // <> --> andNotEqualTo(field)
            // > --> andGreaterThan(field,value)
            // >= --> andGreaterThanOrEqualTo(field,value)
            // < --> andLessThan(field,value)
            // <= --> andLessThanOrEqualTo(field,value)
            // in --> andIn(field,Iterable value)
            // not in --> andNotIn(field,Iterable value)
            // between --> andBetween(field,beginValue,endValue)
            // not like --> andNotLike(field,likeValue)；likeValue 包含‘%’

            // or --> 上述方法的and 都有与之对应的or方法 eg: orEqualTo(field,value)

            //criteria.andEqualTo("yxx",1);设置yxx=1
            /**
             *此方法请根据需要修改下方条件
             */
            //此查询仅针对单表查询，若需要多表查询，尽量使用配置Mapper.xml 和Mapper.java的方式
            //生成条件中均为 and field = value
            //生成代码中，若表结构中有_等字符，生成字段可能会与实体类不同，请注意修改

            boolean flag = false;
            if (parmMap.get("pk") != null && StringUtils.isNotBlank(parmMap.get("pk").toString())) {
                criteria.andEqualTo("pk", parmMap.get("pk").toString().trim());
                flag = true;
            }
            if (parmMap.get("create_date") != null && StringUtils.isNotBlank(parmMap.get("create_date").toString())) {
                criteria.andEqualTo("create_date", parmMap.get("create_date").toString().trim());
                flag = true;
            }
            if (parmMap.get("createor_id") != null && StringUtils.isNotBlank(parmMap.get("createor_id").toString())) {
                criteria.andEqualTo("createor_id", parmMap.get("createor_id").toString().trim());
                flag = true;
            }
            if (parmMap.get("createor_name") != null && StringUtils.isNotBlank(parmMap.get("createor_name").toString())) {
                criteria.andEqualTo("createor_name", parmMap.get("createor_name").toString().trim());
                flag = true;
            }
            if (parmMap.get("conditions") != null && StringUtils.isNotBlank(parmMap.get("conditions").toString())) {
                criteria.andEqualTo("conditions", parmMap.get("conditions").toString().trim());
                flag = true;
            }
            //一个条件都没有的时候给一个默认条件
            if (!flag) {

            }
            PageInfo pageInfo = this.queryPageInfoByExample(example, pageNum, pageSize);
            ResultDto result = new ResultDto();
            result.setRows(pageInfo.getList());
            result.setPage(pageInfo.getPageNum());
            //result.setTotal(pageInfo.getPages());
            result.setTotal((int) pageInfo.getTotal());
            return result;
        } else {
            logger.error("ManulAnalysisServiceImpl.queryListByPage时parmMap数据为空。");
            throw new AppRuntimeException("ManulAnalysisServiceImpl.queryListByPage时parmMap数据为空。");
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void fxData(List<YhkMxJgList> yhkMxJgListList, List<SfMxJgList> sfMxJgListList,
                       AnalysisConditionModel analysisConditionModel) throws Exception {
        Subject currentUser = SecurityUtils.getSubject();
        UserInfo user = (UserInfo) currentUser.getPrincipal();
        List<Map> listYhk = new ArrayList<>();
        List<Map<String, Object>> screenDataList = new ArrayList<>();
        List<Map<String, Object>> pkAndZtpkListYhk = new ArrayList<>();
        String analysisPk = TemplateUtil.genUUID();
        List<String> isNotXdSdYhk = new ArrayList<>();
        for (YhkMxJgList yhkMxJgList : yhkMxJgListList) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("pk", TemplateUtil.genUUID());
            dataMap.put("analysis_pk", analysisPk);
            dataMap.put("type", "1");
            dataMap.put("mxpk", yhkMxJgList.getPk());
            screenDataList.add(dataMap);
            //分析过的不在发主体请求等操作
            if (StringUtils.isNotBlank(yhkMxJgList.getXdrypks())
                    || StringUtils.isNotBlank(yhkMxJgList.getSdrypks())) {
                continue;
            }

            YhkMxQq yhkMxQq = yhkMxQqService.queryYhkMxQqByPrimaryKey(yhkMxJgList.getQqpk());
            //验证账号是否可查询归属行
            BankCode bank = bankCodeService.queryBankByAccount(yhkMxJgList.getJydfzh());
            if (bank == null) {
                isNotXdSdYhk.add(yhkMxJgList.getPk());
            } else {
                String ztpk = TemplateUtil.genUUID();
                Map<String, Object> pkAndZtpkMap = new HashMap<>();
                pkAndZtpkMap.put("pk", yhkMxJgList.getPk());
                pkAndZtpkMap.put("ztqqpk", ztpk);
                pkAndZtpkMap.put("ztqqtype", "1");
                pkAndZtpkListYhk.add(pkAndZtpkMap);

                Map map = new HashMap<>();
                map.put("ztpk", ztpk);
                putData(map, user);
                map.put("jjdpk", yhkMxQq.getJjdpk());
                map.put("subjecttype", bank.getSubjecttype());
                map.put("bankcode", bank.getBankcode());
                map.put("bankname", bank.getBankname());
                map.put("accountname", yhkMxJgList.getJydfmc());
                map.put("cardnumber", yhkMxJgList.getJydfzh());

                String mongoPk = "";
                Example example = new Example(YhkZtQq.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("yxx", 1);
                criteria.andEqualTo("lrdwdm", user.getJgdm());
                criteria.andEqualTo("bankcode", bank.getBankcode());
                criteria.andEqualTo("cardnumber", yhkMxJgList.getJydfzh());
                List<YhkZtQq> qqList = yhkZtQqService.queryListByExample(example);
                if (qqList != null && !qqList.isEmpty()) {
                    mongoPk = qqList.get(0).getFlws();
                } else {
                    mongoPk = znzfService.insertMongo("yhk", "cx", map);
                }
                map.put("flws", mongoPk);
//          	map.put("nlevel", 1);
                listYhk.add(map);
            }
        }

        List<Map> listSf = new ArrayList<>();
        List<Map<String, Object>> pkAndZtpkListSf = new ArrayList<>();
        List<String> isNotXdSdSf = new ArrayList<>();
        for (SfMxJgList sfMxJgList : sfMxJgListList) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("pk", TemplateUtil.genUUID());
            dataMap.put("analysis_pk", analysisPk);
            dataMap.put("type", "2");
            dataMap.put("mxpk", sfMxJgList.getPk());
            screenDataList.add(dataMap);
            //分析过的不在发主体请求等操作
            if (StringUtils.isNotBlank(sfMxJgList.getXdrypks())
                    || StringUtils.isNotBlank(sfMxJgList.getSdrypks())) {
                continue;
            }


            SfMxQq sfMxQq = sfMxQqService.querySfMxQqByPrimaryKey(sfMxJgList.getQqpk());
            String jydfzh = "";
            String jydfmc = "";
            if (sfMxJgList.getJylx().equals("3")) {//转账或提现到银行卡
                //转账到银行卡
                if (!sfMxJgList.getSkyhzh().equals("-") && sfMxJgList.getFkyhzh().equals("-")) {
                    jydfzh = sfMxJgList.getSkyhzh();
                    jydfmc = sfMxJgList.getSkfshmc();
                }
                //提现到到银行卡
                if (sfMxJgList.getSkyhzh().equals("-") && !sfMxJgList.getFkyhzh().equals("-")) {
                    jydfzh = sfMxJgList.getFkyhzh();
                }

                //验证账号是否可查询归属行
                BankCode bank = null;
                if (!"".equals(jydfzh)) {
                    bank = bankCodeService.queryBankByAccount(jydfzh);
                }
                if (bank == null) {
                    isNotXdSdSf.add(sfMxJgList.getPk());
                } else {
                    String ztpk = TemplateUtil.genUUID();
                    Map<String, Object> pkAndZtpkMap = new HashMap<>();
                    pkAndZtpkMap.put("pk", sfMxJgList.getPk());
                    pkAndZtpkMap.put("ztqqpk", ztpk);
                    pkAndZtpkMap.put("ztqqtype", "1");
                    pkAndZtpkListSf.add(pkAndZtpkMap);

                    Map map = new HashMap<>();
                    map.put("ztpk", ztpk);
                    putData(map, user);
                    map.put("jjdpk", sfMxQq.getJjdpk());
                    map.put("subjecttype", bank.getSubjecttype());
                    map.put("bankcode", bank.getBankcode());
                    map.put("bankname", bank.getBankname());
                    map.put("accountname", jydfmc);
                    map.put("cardnumber", jydfzh);

                    String mongoPk = "";
                    Example example = new Example(YhkZtQq.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("yxx", 1);
                    criteria.andEqualTo("lrdwdm", user.getJgdm());
                    criteria.andEqualTo("bankcode", bank.getBankcode());
                    criteria.andEqualTo("cardnumber", jydfzh);
                    List<YhkZtQq> qqList = yhkZtQqService.queryListByExample(example);
                    if (qqList != null && !qqList.isEmpty()) {
                        mongoPk = qqList.get(0).getFlws();
                    } else {
                        mongoPk = znzfService.insertMongo("yhk", "cx", map);
                    }
                    map.put("flws", mongoPk);
//	           	 	map.put("nlevel", 1);
                    listYhk.add(map);
                }

            } else if (sfMxJgList.getJylx().equals("2")) {//支付账户转账
                jydfzh = sfMxJgList.getSkzfzh();
                jydfmc = sfMxJgList.getSkfshmc();

                if (StringUtils.isBlank(jydfzh) || jydfzh.equals("-")) {
                    isNotXdSdSf.add(sfMxJgList.getPk());
                } else {
                    String ztpk = TemplateUtil.genUUID();
                    Map<String, Object> pkAndZtpkMap = new HashMap<>();
                    pkAndZtpkMap.put("pk", sfMxJgList.getPk());
                    pkAndZtpkMap.put("ztqqpk", ztpk);
                    pkAndZtpkMap.put("ztqqtype", "2");
                    pkAndZtpkListSf.add(pkAndZtpkMap);

                    Map map = new HashMap<>();
                    map.put("ztpk", ztpk);
                    putData(map, user);
                    map.put("jjdpk", sfMxQq.getJjdpk());
                    map.put("subjecttype", 1);
                    map.put("paycode", sfMxQq.getPaycode());
                    map.put("payname", sfMxQq.getPayname());
                    map.put("accnumber", jydfzh);
                    //报文生成所需字段
                    map.put("bankname", map.get("payname"));
                    map.put("bankcode", map.get("paycode"));
                    map.put("cardnumber", jydfzh);
                    String mongoPk = "";
                    Example example = new Example(SfZtQq.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("yxx", 1);
                    criteria.andEqualTo("lrdwdm", user.getJgdm());
                    criteria.andEqualTo("paycode", map.get("paycode"));
                    criteria.andEqualTo("accnumber", map.get("accnumber"));
                    List<SfZtQq> qqList = sfZtQqService.queryListByExample(example);
                    if (qqList != null && !qqList.isEmpty()) {
                        mongoPk = qqList.get(0).getFlws();
                    } else {
                        mongoPk = znzfService.insertMongo("sf", "cx", map);
                    }
                    map.put("flws", mongoPk);
//					map.put("nlevel",1);
                    listSf.add(map);
                }
            }
        }

        if (!screenDataList.isEmpty()) {
            if (!listYhk.isEmpty()) {
                yhkZtQqMapper.insertBatchZt(listYhk);
                znzfQueueService.insertBatchZt(listYhk, QqlxEnum.yhkQqlxZtcx.getKey(), (short) 0);
            }

            if (!listSf.isEmpty()) {
                sfZtQqMapper.insertBatchZt(listSf);
                znzfQueueService.insertBatchZt(listSf, QqlxEnum.sfQqlxZtcx.getKey(), (short) 0);
            }

            if (!pkAndZtpkListYhk.isEmpty()) {
                yhkMxJgListMapper.updateByPks(pkAndZtpkListYhk);
            }

            if (!pkAndZtpkListSf.isEmpty()) {
                sfMxJgListMapper.updateByPks(pkAndZtpkListSf);
            }

            if (!isNotXdSdYhk.isEmpty()) {
                yhkMxJgListMapper.updateByIsNotXdSdPks(isNotXdSdYhk);
            }

            if (!isNotXdSdSf.isEmpty()) {
                sfMxJgListMapper.updateByIsNotXdSdPks(isNotXdSdSf);
            }

            ManulAnalysis manulAnalysis = new ManulAnalysis();
            manulAnalysis.setCreate_date(new Date());
            manulAnalysis.setCreateor_name(user.getXm());
            manulAnalysis.setCreateor_id(user.getPk());
            manulAnalysis.setPk(analysisPk);
            manulAnalysis.setConditions(JSON.toJSONString(analysisConditionModel));
            this.insert(manulAnalysis);

            screenDataMapper.insertBatch(screenDataList);

        }


    }

    @Override
    public List<Map> querySfSdListByExample(Map map) throws Exception {
        return screenDataMapper.querySfSdListByExample(map);
    }

    @Override
    public List<Map> querySfXdListByExample(Map map) throws Exception {
        return screenDataMapper.querySfXdListByExample(map);
    }

    @Override
    public List<Map> queryYhkSdListByExample(Map map) throws Exception {
        return screenDataMapper.queryYhkSdListByExample(map);
    }

    @Override
    public List<Map> queryYhkXdListByExample(Map map) throws Exception {
        return screenDataMapper.queryYhkXdListByExample(map);
    }

    private void putData(Map map, UserInfo user) {
        map.put("lrdwdm", user.getJgdm());
        map.put("lrdwmc", user.getJgmc());
        map.put("lrrxm", user.getXm());
        map.put("lrrjh", user.getJh());
        map.put("reason", Constants.SY);
    }
}
